package com.zjgxzh.dialogservice.controller;

import com.zjgxzh.dialogservice.pojo.Dialog;
import com.zjgxzh.dialogservice.pojo.ResponseDialog;
import com.zjgxzh.dialogservice.pojo.Summary;
import com.zjgxzh.dialogservice.pojo.ThreadIdPost;
import com.zjgxzh.dialogservice.service.DialogService;
import com.zjgxzh.dialogservice.service.SummaryService;
import com.zjgxzh.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

import static com.zjgxzh.dialogservice.controller.ThreadController.mapOf;

@CrossOrigin
@RestController
@RequestMapping("/summary")
public class SummaryController {

    @Autowired
    private SummaryService summaryService;
    @Autowired
    private DialogService dialogService;

    @PostMapping("/get")
    public Result<Summary> get(@RequestBody ThreadIdPost post){
        //根据post.threadId拿到Summary
        Summary summary = summaryService.findSummaryByThreadId(post.getThreadId());
        return Result.success(summary);
    }

    @PostMapping("/run")
    public Result<?> run(@RequestBody ThreadIdPost post){
        //根据post.threadId拿到Dialog的所有数据
        //然后要运行一下RAGFlow让它输出总结
        //把总结的内容记录进Summary表
        //TODO
        List<Dialog>list = dialogService.findDialogByThreadId(post.getThreadId());
        if (!list.isEmpty()){
            String key = list.get(0).getAssistantId();
            RestTemplate restTemplate = new RestTemplate();
            HttpEntity<Map<String, Object>> request = mapOf((map)->{
                map.put("inputs", null);
                map.put("query", "请帮我总结一下本次面试情况");
                map.put("response_mode", "blocking");
                map.put("user", "zjgxzh");
                map.put("files", null);
                map.put("conversation_id", post.getThreadId());
            }, key);
            ResponseDialog resDialog = restTemplate.postForObject("https://api.dify.ai/v1/chat-messages", request, ResponseDialog.class );
            String username = list.get(0).getUsername();
            Summary summary = ResponseDialog.summary(resDialog,username);
            if (summaryService.findSummaryByThreadId(summary.getThreadId())==null){
                summaryService.addSummary(summary);
            }
            else {
                summaryService.updateSummary(summary);
            }
            return Result.success(summary);
        }
        else {
            return Result.error("未找到面试记录");
        }
    }
}
